package com.mokairui.sort.advanced;

import java.util.Arrays;

/**
 * @Description
 * @Author Mokairui
 * @Since 2021/11/2
 */
public class Bubble {
    public static void main(String[] args) {
        int[] array = {8, 10, 11, 40, 22, 27, 2, 8, 18};
//        sort(array);
        sort_v2(array);
        System.out.println(Arrays.toString(array));
    }

    private static void sort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            boolean swap = false; // 标记是否发生过交换, 没有发生则可以结束比较
            for (int j = 0; j < array.length - 1; j++) {
                if (array[j] > array[j + 1]) {
                    swap(array, j, j + 1);
                    swap = true;
                }
            }
            if (!swap) {
                break;
            }
        }
    }

    private static void sort_v2(int[] array) {
        int n = array.length - 1;
        for (;;) {
            int last = 0; // 表示最后一次交换的索引
            for (int j = 0; j < n; j++) {
                if (array[j] > array[j + 1]) {
                    swap(array, j, j + 1);
                    last = j;
                }
            }
            n = last;
            if (n == 0) {
                break;
            }
        }
    }

    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
